<template>
    <view class="navigation">
        <eui-navbar ref="EuiNavBar" title="对比统计" displayable="true" color="#000000" backgroundColor="#FFFFFF"
            rightIcon="" rightIcon5="icon-qiehuan" rightText="" :showPopup="false" @clickRight="clickNavbarRight">
        </eui-navbar>
        <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
            <view>
                <eui-tab :tabs="tabData" tabStyle="margin: 0 80rpx" :value="tabIndex" @change="tabChange"
                    showBadge="true">
                </eui-tab>
            </view>
            <view v-if="tabIndex == 0">
                <eui-card title="" titleDesc="">
                    <TableCard :column="storeColumn2" :listData="storeTableData2" :compareTable="true">
                    </TableCard>
                </eui-card>
            </view>
            <view v-if="tabIndex != 0">
                <view style=" background-color: #FFF; width:100%;height: 100rpx;">
                    <scroll-view
                        style="-ms-overflow-style: none; scrollbar-width: thin; scrollbar-color: transparent transparent; "
                        scroll-x="true" show-scrollbar="false">
                        <eui-card-input v-model="formData.c_level" :range="levelSelect" titleWidth='20'
                            style="padding:0rpx 30rpx;" v-if="formData.c_type === '2' || formData.c_type === '3'"
                            h-padding="0" alignType="left" type="radio" rightIconType="right" @buttonClick="levelChange"
                            :showBottomLine="false" flexWrap="nowrap" />
                    </scroll-view>
                </view>
                <eui-search-bar :foucs="true" v-model="searchText" placeholder="输入名称筛选数据" v-if="isCardOrChart"
                    @confirm="searchConfirm" radius="30">
                </eui-search-bar>
                <scroll-view class="scroll-content" scroll-y="true" ref="scrollView" :scroll-top="scrollTopValue"
                    :style="`width: 100%;height:${scrollHeightChange}rpx;box-sizing: border-box;overflow-y: scroll;`">
                    <eui-card :sort="`${index + 1}`"
                        :sortStyle="`margin-bottom:4rpx;margin-right:8rpx;font-size: 30rpx;font-weight: 600;color:${index < 3 ? '#FFA500' : '#919191'}`"
                        :title="`${item.title || '无'}`" v-for="(item, index) in dataList" :key="index"
                        v-if="isCardOrChart">
                        <view
                            style="width: 100%; display: grid;grid-template-columns: 33.33% 33.33% 33.33%; padding: 4rpx;">
                            <stat-item title="销售金额" :value="item.current.c_at_sale"
                                :compareValue="item.compare.c_at_sale" :compareTitle="compareTitle"></stat-item>
                            <stat-item title="来客数" :value="item.current.c_sale_count" :precision="0"
                                :compareValue="item.compare.c_sale_count" :compareTitle="compareTitle"></stat-item>
                            <stat-item title="客单价(元)" :value="item.current.c_atv" :compareValue="item.compare.c_atv"
                                :compareTitle="compareTitle"></stat-item>
                            <stat-item title="折扣金额" :value="item.current.c_disc_value"
                                :compareValue="item.compare.c_disc_value" :compareTitle="compareTitle"></stat-item>
                            <stat-item title="毛利率(%)" :value="item.current.c_gross_margin"
                                :compareValue="item.compare.c_gross_margin" :compareTitle="compareTitle"></stat-item>
                            <stat-item title="毛利额" :value="item.current.c_gross_profit"
                                :compareValue="item.compare.c_gross_profit" :compareTitle="compareTitle"></stat-item>
                        </view>
                    </eui-card>
                    <eui-card title="销售对比" titleDsec="最多展示前20名" :key="index" v-if="!isCardOrChart">
                        <template v-slot:extra>
                            <view style="justify-content: flex-end;font-size: 26rpx;">
                                <eui-combox selectWidth="120rpx" v-model="formData.c_amount_type" valueColor="#666666"
                                    backgroundColor="#F8F8F8" :border="false" :candidates="amountTypeOpts"
                                    fieldName="value" @selectChange="onAmountTypeChange">
                                </eui-combox>
                            </view>
                        </template>
                        <view style="width: 100%;padding: 4rpx;">
                            <view>
                                <eui-lime-chart :option="saleChartOption" :chartStyle="saleChartStyle" />
                            </view>
                        </view>
                    </eui-card>
                </scroll-view>
            </view>
            <!-- <view class="header">
				<eui-card title="统计类型">
					<template v-slot:extra>
						<eui-combox selectWidth="80rpx" v-model="formData.c_type" valueColor="#666666"
							backgroundColor="#F8F8F8" :border="false" :candidates="manaTypeList" :fieldName="value"
							@selectChange="detailTypeChange">
						</eui-combox>
					</template>
<eui-card-input v-model="formData.c_level" :range="levelSelect" titleWidth='60' placeholder="请选择层级" title="层级"
    v-if="formData.c_type === '2' || formData.c_type === '3'" h-padding="0" alignType="left" type="radio"
    rightIconType="right" @buttonClick="levelChange" :showBottomLine="false" />
</eui-card>
</view> -->

            <!-- <scroll-view class="scroll-content" scroll-y="true"
                :style="`width: 100%;height:${scrollHeight}rpx;box-sizing: border-box;overflow-y: scroll;`">
                <eui-card title="" v-for="(item, index) in detailList" :key="index">
                    <view style="width: 100%; background-color: #F9FAFC;">
                        <view style="width: 100%; display: flex; flex-wrap: wrap; margin: 20rpx;">
                            <view style="width: 100%;">
                                {{ item.title }}
                            </view>
                            <view style="width: 50%;">
                                <compare-item title1="销售金额" :value1="item.current.c_at_sale" :title2="compareTitle"
                                    :value2="item.compare.c_at_sale"></compare-item>
                            </view>
                            <view style="width: 50%;">
                                <compare-item title1="销售占比%" :value1="item.current.c_at_sale_rate"
                                    :title2="compareTitle" :value2="item.compare.c_at_sale_rate"
                                    method="minus"></compare-item>
                            </view>
                            <view style="width: 50%;">
                                <compare-item title1="来客数" :value1="item.current.c_sale_count" :title2="compareTitle"
                                    :value2="item.compare.c_sale_count" :precision="0"></compare-item>
                            </view>
                            <view style="width: 50%;">
                                <compare-item title1="客单价(元)" :value1="item.current.c_atv" :title2="compareTitle"
                                    :value2="item.compare.c_atv"></compare-item>
                            </view>
                            <view style="width: 50%;">
                                <compare-item title1="毛利额" :value1="item.current.c_gross_profit" :title2="compareTitle"
                                    :value2="item.compare.c_gross_profit"></compare-item>
                            </view>
                            <view style="width: 50%;">
                                <compare-item title1="毛利率%" :value1="item.current.c_gross_margin" :title2="compareTitle"
                                    :value2="item.compare.c_gross_margin" method="minus"></compare-item>
                            </view>
                        </view>
                    </view>
                </eui-card>
            </scroll-view> -->
        </view>
    </view>
</template>

<script setup type="ts">
import { onMounted, ref, reactive, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateStores, validateGds, defaultMapping, validateStoresAndWno } from '@/hooks/useValidateMethod';
import { todayAdd, formatNow } from '@/hooks/useUtils';
import service from "@/common/service";
import { getRdsUrl, rdsRequest, rdsRequestAsync } from '@/hooks/rdsServices';
import { calcAtInByPt, validateOddLot, round, calcPtInByPtPay, calcPetpayByPtPay } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { getRelatedName, getDictName, getUserDictSelectList, getUserDictName, getDictSelectList, getWeightUnits, getDictList } from '../components/RelatedName.js';
import { init, getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import { validateAdnoLevel } from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";
import TableCard from '@/components/TableCard.vue';
import dayjs from 'dayjs';
import StatItem from "./StatItem.vue";
import numeral from 'numeral';
import { useProRelatedNameHook } from '@/hooks/useProRelatedName';

const { mapChannel } = useProRelatedNameHook();

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300);

const searchText = ref(null);
const searchPopup = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
// const tabData = ref([{ name: '门店' }, { name: '渠道' }, { name: '部门' }, { name: '品类' }]);
const tabData = ref([{ name: '门店' }, { name: '部门' }, { name: '品类' }]);

const isCardOrChart = ref(true);
const tabIndex = ref(0);
const spaceLeft = ref(10);
const dataList = ref([]);
// 系统参数，字典
const sysConfig = ref({
    adnoLevel: [],
    gdsclassLevel: [],
});


const scrollTopValue = onMounted(() => {
    return 0;
})
const searchConfirm = async () => {
    await detailList();
}
const tabChange = async (value) => {
    searchText.value = '';
    formData.value.c_level = 1;
    tabIndex.value = value;
    // if (value == 0) {
    //     formData.value.c_type = '1';
    // } else if (value == 1) {
    //     formData.value.c_type = '6';
    // } else if (value == 2) {
    //     formData.value.c_type = '2';
    // } else if (value == 3) {
    //     formData.value.c_type = '3';
    // }
    if (value == 0) {
        formData.value.c_type = '1';
    } else if (value == 1) {
        formData.value.c_type = '2';
    } else if (value == 2) {
        formData.value.c_type = '3';
    }
    await searchData();
}

const storeColumn2 = ref([
    {
        title: '门店', // th标题
        isFixed: true, // 是否固定
        key: 'c_store_name', // 对应字段，
        align: 'left',
        width: 1, // 宽度 width * 100 rpx
    },
    {
        title: '销售金额', // th标题
        isFixed: false, // 是否固定
        key: 'c_at_sale', // 对应字段
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
        //slot: 'b' // 插槽名
    },
    {
        title: '毛利额', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '毛利率(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_margin', // 对应字段
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
        //slot: 'c' // 插槽名
    },
    {
        title: '交易笔数', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_count',
        align: 'right',
        width: 1.5,
        compare: true,
    },
    {
        title: '客单价(元)', // th标题
        isFixed: false, // 是否固定
        key: 'c_atv',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '销售占比(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_rate',
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
    },
    {
        title: '毛利占比(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit_rate',
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
    },
]);


const currentDetail = ref([])
const compareDetail = ref([])

const currentSum = computed(() => {
    return calcSum(currentData.value);
})

const compareSum = computed(() => {
    return calcSum(compareData.value);
})

const clickNavbarRight = () => {
    isCardOrChart.value = !isCardOrChart.value;
}

const levelSelect = computed(() => {
    if (formData.value.c_type === '2') {
        return sysConfig.value.adnoLevel;
    } else if (formData.value.c_type === '3') {
        return sysConfig.value.gdsclassLevel;
    }
    return [];
});


const amountTypeOpts = reactive([
    { text: '销售额', value: 'c_at_sale' },
    // { text: '交易数', value: 'c_sale_count' },
    { text: '毛利额', value: 'c_gross_profit' },
    { text: '毛利率', value: 'c_gross_margin' }
])

const onAmountTypeChange = async (value) => {
    await formatSaleData();
}

const getCodeRuleLevel = async (c_type) => {
    // 获取部门层级
    // c_type === 'adno' : 'gdsclass';
    let result = [];
    const length = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'GetCodeRuleLevel', c_type);
    if (length >= 0) {
        result = Array.from({ length: length }, (_, i) => ({ text: i + 1, value: i + 1 }));
    }
    return result;
}

// 获取系统参数、字典
const getSysConfig = async () => {
    sysConfig.value.adnoLevel = await getCodeRuleLevel('adno');
    sysConfig.value.adnoLevel.map(f => f.text = getUserDictName('部门层级', f.value + ''));
    sysConfig.value.gdsclassLevel = await getCodeRuleLevel('gdsclass');
    sysConfig.value.gdsclassLevel.map(f => f.text = getUserDictName('品类层级', f.value + ''));
}

// 设置默认值
const setDefault = async () => {
    const { loginInfo } = mainStore;
    sUserStore.value = loginInfo.sUserStore;
    sUserStoreName.value = loginInfo.sUserStoreName;
    sUser.value = loginInfo.sUser;
    formData.value.c_store_id = loginInfo.sUserStore;
}

onMounted(() => {
    getListHeight()
})
const scrollHeight = ref(300);
const scrollHeightChange = computed(() => {
    let height = scrollHeight.value;
    //重新计算高度
    if (['2', '3'].includes(formData.value.c_type)) {
        // const levelHeight = Math.ceil(levelSelect.value.length / 5) * 80;
        const levelHeight = 80;
        height = scrollHeight.value - levelHeight;
    }
    if (!isCardOrChart.value) {
        height = height + 70;
    }
    return height;
});

// 获取列表高度
const getListHeight = async () => {
    await uni.getSystemInfo({
        success: function (res) { // res - 各种参数
            let info = uni.createSelectorQuery().select(".footer-view");
            info.boundingClientRect(function (data) { //data - 各种参数
                //获取列表高度
                let height = res.windowHeight - data.top;
                //转换rpx
                listHeight.value = height / (res.windowWidth / 750) - 100;
                scrollHeight.value = (res.windowHeight - data.top - 100) / (res.windowWidth / 750);
            }).exec()
        }
    });
};
// 查询表单
const formData = ref({
    c_current_type: '1',
    c_amount_type: 'c_at_sale',
    c_sale_da: dayjs().format('YYYY-MM-DD'),
    c_sale_da_en: dayjs().format('YYYY-MM-DD'),
    c_sale_da2: dayjs().format('YYYY-MM-DD'),//对期
    c_sale_da2_en: dayjs().format('YYYY-MM-DD'),//对期
    c_is_compare: true,  //比上周
    c_type: '2', //1-机构, 2-部门, 3-品类
    c_level: 1, //
    c_store_id: '',
    c_p_id: '',
    c_unit_type: '1'
})
const currentData = ref([])
const compareData = ref([])
// 查询数据接口
const searchData = async () => {
    service.enjoyShowLoading('正在加载...');
    await queryStoreSale2();
    await querySaleData();
    service.enjoyHideLoading();
}

const querySaleData = async () => {
    const objectData = {
        c_level: formData.value.c_level,
        c_p_id: "",
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_type == '1' ? mainStore.loginInfo.sUserStore : '',
        c_type: formData.value.c_type,
        c_is_compare: true,
    };
    const result = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'QueryCurSaleMBM', objectData, '881',);
    currentData.value = result?.currentData.filter(x => x.c_at_sale != 0 || x.c_sale_count != 0 || x.c_atv != 0);
    compareData.value = result?.compareData.filter(x => x.c_at_sale != 0 || x.c_sale_count != 0 || x.c_atv != 0);

    await detailList();
    await formatSaleData();
}

const currentStoreSaleTableData2 = ref([]);
const compareStoreSaleTableData2 = ref([]);
const queryStoreSale2 = async (type, storeId) => {
    const saletRendReq = {
        ...formData.value,
        c_type: '1',
        c_is_compare: true,
        c_store_comparable: '1'
    }
    const saleTrendResult = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'QueryCurSaleRateRegion', saletRendReq, '881',);
    currentStoreSaleTableData2.value = saleTrendResult?.currentData;
    compareStoreSaleTableData2.value = saleTrendResult?.compareData;

    await formatStoreSaleTableData2();
    // await formatStoreSaleChartData2();
}
const storeTableData2 = ref([]);
const formatStoreSaleTableData2 = async () => {
    let ids = [...currentStoreSaleTableData2.value?.map(f => f.c_id), ...compareStoreSaleTableData2.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);

    const currentSum = calcSumList(currentStoreSaleTableData2.value);
    const compareSum = calcSumList(compareStoreSaleTableData2.value);

    const list = ids.map(x => {
        const current = calcUnit(currentStoreSaleTableData2.value.find(f => f.c_id == x) || { ...defaultSum });
        const compare = calcUnit(compareStoreSaleTableData2.value.find(f => f.c_id == x) || { ...defaultSum });

        const c_sale_rate_currrent = currentSum.c_at_sale == 0 ? 0 : (((current.c_at_sale / currentSum.c_at_sale) * 10000) / 100).toFixed(2);
        const c_gross_profit_rate_currrent = currentSum.c_gross_profit == 0 ? 0 : (((current.c_gross_profit / currentSum.c_gross_profit) * 10000) / 100).toFixed(2);;

        const c_sale_rate_compare = compareSum.c_at_sale == 0 ? 0 : (((compare.c_at_sale / compareSum.c_at_sale) * 10000) / 100).toFixed(2);
        const c_gross_profit_rate_compare = compareSum.c_gross_profit == 0 ? 0 : (((compare.c_gross_profit / compareSum.c_gross_profit) * 10000) / 100).toFixed(2);

        return {
            title: getRelatedName("rdsStores", x) || x,
            current: { ...current, c_store_name: getRelatedName("rdsStores", x) || x, c_sale_rate: c_sale_rate_currrent, c_gross_profit_rate: c_gross_profit_rate_currrent },
            compare: { ...compare, c_store_name: getRelatedName("rdsStores", x) || x, c_sale_rate: c_sale_rate_compare, c_gross_profit_rate: c_gross_profit_rate_compare },
            option: {
                c_at_sale: !compare.c_at_sale ? 0 : (current.c_at_sale - compare.c_at_sale) / compare.c_at_sale * 100,
                c_gross_profit: !compare.c_gross_profit ? 0 : (current.c_gross_profit - compare.c_gross_profit) / compare.c_gross_profit * 100,
                c_gross_margin: (current.c_gross_margin - compare.c_gross_margin),
                c_sale_count: !compare.c_sale_count ? 0 : (current.c_sale_count - compare.c_sale_count) / compare.c_sale_count * 100,
                c_atv: !compare.c_atv ? 0 : (current.c_atv - compare.c_atv) / compare.c_atv * 100,
                c_sale_rate: (c_sale_rate_currrent - c_sale_rate_compare)  || 0,
                c_gross_profit_rate: (c_gross_profit_rate_currrent - c_gross_profit_rate_compare)  || 0,
            }
        }
    })


    // 添加全部
    list.push({
        title: '全部区域',
        current: { ...currentSum, c_store_name: '全部区域', c_sale_rate: 100, c_gross_profit_rate: 100, c_perm: 100 },
        compare: { ...compareSum, c_store_name: '全部区域', c_sale_rate: 100, c_gross_profit_rate: 100, c_perm: 100 },
        option: {
            c_at_sale: !compareSum.c_at_sale ? 0 : (currentSum.c_at_sale - compareSum.c_at_sale) / compareSum.c_at_sale,
            c_gross_profit: !compareSum.c_gross_profit ? 0 : (currentSum.c_gross_profit - compareSum.c_gross_profit) / compareSum.c_gross_profit,
            c_gross_margin: (currentSum.c_gross_margin - compareSum.c_gross_margin),
            c_sale_count: !compareSum.c_sale_count ? 0 : (currentSum.c_sale_count - compareSum.c_sale_count) / compareSum.c_sale_count,
            c_atv: !compareSum.c_atv ? 0 : (currentSum.c_atv - compareSum.c_atv) / compareSum.c_atv,
            c_sale_rate: (currentSum.c_sale_rate - compareSum.c_sale_rate) || 0,
            c_gross_profit_rate: (currentSum.c_gross_profit_rate - compareSum.c_gross_profit_rate) || 0,
        }
    });
    storeTableData2.value = list
}


const calcUnit = (item) => {
    const sum = { ...item }
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;
    sum.c_atv = sum.c_atv;
    sum.c_at_sale = sum.c_at_sale / unit;
    sum.c_sale_value = sum.c_sale_value / unit;
    sum.c_gross_profit = sum.c_gross_profit / unit;
    sum.c_disc_value = sum.c_disc_value / unit;
    return sum;
}


const saleChartDataY = ref([])
const saleChartDataX = ref([]);
const saleChartStyle = computed(() => {
    let style = "height: 500rpx;background: #FFFFFF";
    if (saleChartDataX.value.length > 4) {
        const height = saleChartDataX.value.length * 130;
        style = `height: ${height}rpx;background: #FFFFFF`;
    }
    return style;
});
const saleChartOption = computed(() => {
    return {
        title: {
            text: ''
        },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            top: '0%',
            itemHeight: 8,
        },
        grid: {
            left: '-1%',
            right: '0%',
            bottom: '3%',
            top: '3%',
            containLabel: true
        },
        xAxis: {
            boundaryGap: [0, 0.01],
            width: 20,
            splitLine: {
                show: false // 不显示网格线
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            axisLabel: {
                rotate: 45
            },
            type: 'value',
        },
        yAxis: {
            type: 'category',
            axisLabel: {
                rotate: 45
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            // axisLine: {
            //     show: false, // 不显示坐标轴线
            // },
            data: saleChartDataX.value
        },
        series: saleChartDataY.value,
    }
});

const formatSaleData = async () => {
    saleChartDataY.value = [];
    const amountType = formData.value.c_amount_type || 'c_at_sale';
    let ids = [...currentData.value?.map(f => f.c_id), ...compareData.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);

    let classType = 'rdsStores';
    if (formData.value.c_type == '2') {
        classType = 'rdsDeparts';
    }
    else if (formData.value.c_type == '3') {
        classType = 'rdsGdsclasses';
    }
    const list = ids.map(id => {
        const current = currentData.value.find(f => f.c_id == id);
        const compare = compareData.value.find(f => f.c_id == id);
        return {
            title: formData.value.c_type == '6' ? mapChannel.value[id] || id || '其它' : getRelatedName(classType, id) || id || '其它',
            current: calcUnit(current || { ...defaultSum }),
            compare: calcUnit(compare || { ...defaultSum })
        }
    })

    list.sort((a, b) => a.current[amountType] - b.current[amountType]);
    //只显示前20条
    const frist20List = list.slice(0, 20);
    saleChartDataX.value = frist20List.map(x => { return x.title });


    saleChartDataY.value.push({
        name: '本期',
        type: 'bar',
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: frist20List.map(f => f.current[amountType]),
        barWidth: '30%',
        label: {
            show: true, // 显示标签
            distance: 3,
            borderWidth: 100,
            position: ['50%', '50%'], // 标签位置
            formatter: function (params) {
                return numeral(params.data).format('0,0.00')
            },
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
    saleChartDataY.value.push({
        name: '对期',
        type: 'bar',
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: frist20List.map(f => f.compare[amountType]),
        barWidth: '30%',
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            // 可以通过 formatter 自定义标签格式
            formatter: function (params) {
                return numeral(params.data).format('0,0.00')
            },
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })

}

const defaultSum = {
    c_at_sale_rate: 0,
    c_at_sale: 0,
    c_sale_value: 0,
    c_atv: 0,
    c_sale_count: 0,
    c_gross_profit: 0,
    c_gross_margin: 0,
    c_disc_value: 0
}

onLoad(async ({
    c_sale_da, c_sale_da_en, c_sale_da2, c_sale_da2_en,
    c_store_id, c_level, c_unit_type, c_current_type
}) => {
    formData.value.c_sale_da = c_sale_da;
    formData.value.c_sale_da_en = c_sale_da_en;
    formData.value.c_sale_da2 = c_sale_da2;
    formData.value.c_sale_da2_en = c_sale_da2_en;
    formData.value.c_store_id = c_store_id;
    formData.value.c_level = c_level;
    formData.value.c_unit_type = c_unit_type;
    formData.value.c_current_type = c_current_type;
    await init();
    await getSysConfig();
    // await setDefault();
    await searchData();
})

// 顶部统计
const currentTypeOpts = reactive([
    { text: '昨日', value: '1' },
    { text: '上周', value: '2' },
    { text: '上月', value: '3' },
    { text: '对期', value: '4' }
])

const compareTitle = computed(() => {
    const name = currentTypeOpts.find(f => f.value == formData.value.c_current_type)?.text;
    return name;
})

const calcSumList = (items) => {
    const sum = (items || []).reduce((p, v) => {
        return {
            c_at_sale: p.c_at_sale + v.c_at_sale,
            c_sale_value: p.c_sale_value + v.c_sale_value,
            c_atv: 0,
            c_sale_count: p.c_sale_count + v.c_sale_count,
            c_gross_profit: p.c_gross_profit + v.c_gross_profit,
            c_gross_margin: p.c_gross_margin + v.c_gross_margin,
            c_gross_profit_pro: p.c_gross_profit_pro + v.c_gross_profit_pro,
            c_gross_margin_pro: p.c_gross_margin_pro + v.c_gross_margin_pro,
            c_disc_value: p.c_disc_value + v.c_disc_value,
            c_at_sale_mem: p.c_at_sale_mem + v.c_at_sale_mem,
            c_at_sale_pro: p.c_at_sale_pro + v.c_at_sale_pro,
            c_cost_inv: p.c_cost_inv + v.c_cost_inv,
            c_inv_days: p.c_inv_days + v.c_inv_days,
            c_gmroi: p.c_gmroi + v.c_gmroi,
        }
    }, { ...defaultSum });
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;

    sum.c_gross_margin = sum.c_at_sale == 0 ? 0 : sum.c_gross_profit / sum.c_at_sale * 100;
    sum.c_atv = sum.c_sale_count == 0 ? 0 : sum.c_at_sale / sum.c_sale_count;
    sum.c_at_sale = sum.c_at_sale / unit;
    sum.c_sale_value = sum.c_sale_value / unit;
    sum.c_gross_profit = sum.c_gross_profit / unit;
    sum.c_disc_value = sum.c_disc_value / unit;
    sum.c_at_sale_mem = sum.c_at_sale_mem / unit;
    sum.c_at_sale_pro = sum.c_at_sale_pro / unit;
    sum.c_cost_inv = sum.c_cost_inv / unit;
    sum.c_inv_days = sum.c_inv_days || 0;
    sum.c_gross_margin_pro = (sum.c_gross_margin_pro * 100) || 0;
    sum.c_gmroi = (sum.c_gmroi * 100) || 0;
    return sum;
}

const calcSum = (item) => {
    const sum = { ...item }
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;
    sum.c_atv = sum.c_atv;
    sum.c_at_sale = sum.c_at_sale / unit;
    sum.c_sale_value = sum.c_sale_value / unit;
    sum.c_gross_profit = sum.c_gross_profit / unit;
    sum.c_disc_value = sum.c_disc_value / unit;
    return sum;
}

const detailList = async () => {
    let ids = [...currentData.value?.map(f => f.c_id), ...compareData.value?.map(f => f.c_id)]
    ids = ids.filter((f, index) => ids.indexOf(f) == index)

    let classType = 'rdsStores';
    if (formData.value.c_type == '2') {
        classType = 'rdsDeparts';
    }
    else if (formData.value.c_type == '3') {
        classType = 'rdsGdsclasses';
    }
    const list = ids.map(id => {
        return {
            title: formData.value.c_type == '6' ? mapChannel.value[id] || id : getRelatedName(classType, id) || id,
            current: calcSum(currentData.value?.find(f => f.c_id == id) || { ...defaultSum }),
            compare: calcSum(compareData.value?.find(f => f.c_id == id) || { ...defaultSum })
        }
    })
    list.sort((a, b) => b.current.c_at_sale - a.current.c_at_sale);
    if (searchText.value) {
        dataList.value = list.filter(f => f.title.includes(searchText.value));
        return;
    }
    dataList.value = list;
}

const levelChange = async (e) => {
    formData.value.c_level = e;
    await searchData();
}
</script>

<style lang="scss" scoped>
@import '../../../main.scss';

.navigation {
    display: flex;
    height: 100vh;
    width: 100%;
    flex-direction: column;
    background: #F2F2F2;
}

.top-view {
    width: 100%;
    height: 0rpx;
    background: #FFFFFF;
    margin-bottom: 20rpx;
}

.extra-view {
    margin-right: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60rpx;
    height: 100%;
}

.footer-view {
    width: 100%;
    flex: 1;
}

.list-scroll {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}

.bottom-view {
    width: 100%;
    height: 100rpx;
    background: #FFFFFF;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-direction: row;
}

.center-style {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    margin-right: 20rpx;
    //gap: 20rpx;
}

.gap-view {
    width: 20rpx;
    height: auto;
}

//内容行
.item-view {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    align-items: center;
    margin-top: 16rpx;
    row-gap: 8rpx;
}

.line-view {
    width: 100%;
    height: 1rpx;
    background: #EEEEEE;
    margin: 20rpx 0;
}

.popup-content {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0;
    width: 100%;
    background-color: #ffffff;
}

.popup-bottom {
    background: #ffffff;
    border-top: 1rpx solid $uni-line-color;
    display: flex;
    justify-content: center;
    padding: 20rpx;
}
</style>